<template>
	<a-modal title="完成入库" :width="1200" :visible="visible" :confirmLoading="confirmLoading" :footer="null"
		@ok="handleSubmit" @cancel="handleCancel">
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="8" :sm="24" v-if="false">
							<a-form-item label="订单ID">
								<a-input v-model="queryParam.orderId" placeholder="请输入订单ID" />
							</a-form-item>
						</a-col>

					</a-row>
				</a-form>
			</div>

			<s-table ref="table" class="table-operator" size="default" :columns="columnsDynamic" :data="loadData"
				:alert="true" :rowKey="(record) => record.code"
				:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :showPagination="false">

				<template slot="materialModelNumber" slot-scope="text, record">
					{{ record.material ? record.material.materialModelNumber : '' }}
				</template>
				<!-- <span slot="image" slot-scope="text">
					<image-preview :images="text" />
				</span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.imageUrl" />
				</span>
				<span slot="action" slot-scope="text, record">
					<a @click="handleMultipleInStore([record])">入库</a>
				</span>
			</s-table>

			<div>
				<a-button type="primary" @click="handleMultipleInStore(selectedRows)">入库</a-button>
			</div>

		</a-card>
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import { page, del, add } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { addSimple, addAllType } from '@/api/modular/main/emsorder/emsOrderManage'

export default {
	components: {
		STable,
	},
	data() {
		return {
			title: null,
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			visible: false,
			confirmLoading: false,
			emsOrder: null,
		}
	},
	watch: {
	},
	computed: {
		columnsDynamic() {

			let result = [       // 表头
				{
					title: '序号', width: '80px',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '供应商',
					dataIndex: 'orgIdSupplierName'
				},
				{
					title: '总数量',
					dataIndex: 'number'
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '150px',
					scopedSlots: { customRender: 'action' }
				}
			]
			//如果是线缆管理员
			if (this.isSubOrg) {
				let index1 = result.findIndex(value => value.title == '供应商')
				//如果是供应商，删除此列
				if (index1 > -1) {
					result.splice(index1, 1)
				}
			}
			return result
		},
		isSubOrg() {
			return this.hasRole(this.$util.ROLE_ENUM.MATERIAL_ADMIN3.id)
		},
		token() {
			return this.$ls.get(ACCESS_TOKEN)
		}
	},
	methods: {
		show(record, materialType) {
			this.visible = true
			this.emsOrder = record
			this.queryParam.pageSize = -1
			this.queryParam.orderId = record.orderId
			this.queryParam.materialType = materialType
			this.queryParam.executeStatus = this.$businessEnum.EXECUTE_STATUS_ENUM.IN_PROGRESS.id
			setTimeout(() => {
				this.$refs.table.clearSelected()
				this.handleOk()
			}, 100)
		},

		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		handleSubmit() {
		},
		handleCancel() {
			this.visible = false
		},
		onEmsMaterialIndex1Selected(materialRow) {
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			// debugger
			let { materialId, materialName, materialCode, materialType, costPrice } = materialRow
			// 需要调用接口往订单中添加物料
			let _emsOrder = Object.assign({}, this.emsOrder)
			_emsOrder.orderMaterials = []
			let orderMaterial = {
				orderMaterialId: '',
				orderId: _emsOrder.orderId,
				bomId: '0',  // 单独选择原料时没有BOMID
				materialId: materialId,
				number: 1,
				completedNumber: 0,
				executeStatus: '0',
				executeProgress: '0',
				status: '0',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			}
			_emsOrder.orderMaterials.push(orderMaterial)
			add(orderMaterial).then(res => {
				if (res.success) {
					this.$message.success('新增成功')
					// this.handleCancel()
					this.$emit('ok', values)
					this.$refs.table.refresh()
				} else {
					this.$message.info('新增失败：' + res.message)
				}
			})
			// 然后刷新table控件
		},
		handleMultipleInStore(rows) {
			let order = this.emsOrder
			let orderMaterials = rows

			let orderMaterialParams = orderMaterials.map(value => {
				return {
					orderMaterialId: '',
					orderId: '',
					sourceOrderId: value.orderId,
					sourceOrderMaterialId: value.orderMaterialId,
					bomId: '0',
					materialId: value.materialId,
					number: value.number,
					extraNumber: 0,
					completedNumber: value.number,
					executeStatus: this.$businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id,
					executeProgress: 100,
					file: '',
					remark: '',
					markAbnormal: '0',
					status: '',
					createTime: '',
					createUser: '',
					updateTime: '',
					updateUser: '',
				}
			})

			if (orderMaterialParams.length == 0) {
				this.$message.error('请先选择关联物料')
				return
			}

			let orderParam = {
				orderId: '',
				sourceOrderId: order.orderId,
				orderParentId: '',
				orderPids: '',
				orderNumber: '',
				orderType: this.$businessEnum.ORDER_TYPE_ENUM.inOrder.id,
				orgId: '',
				targetOrgId: '',
				isOverseasStore: '',
				countryCode: '',
				file: '',
				remark: '',
				executeStatus: this.$businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id,
				executeProgress: 100,
				issueTime: '',
				estimateCompletionTime: '',
				receiveTime: '',
				status: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				orderMaterials: orderMaterialParams,
				materialPoolIds: null,
			}

			addAllType(orderParam).then((res) => {
				this.confirmLoading = false
				if (res.success) {
					this.$message.success('新增成功')
					this.handleCancel()
					this.$emit('ok', orderParam)
				} else {
					this.$message.info('新增失败：' + res.message)
				}
			}).finally((res) => {
				this.confirmLoading = false
			})
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
